package bbs.mvc.Servlet;

import bbs.mvc.Beans.DBUtils;
import bbs.mvc.Beans.Posting;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "postiServlet", value = "/posti")
public class PostiServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            List<Posting> postings = DBUtils.getPostings();

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            try(Writer writer = response.getWriter()) {
                writer.write(this.toJson(postings));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private String toJson(List<Posting> postings) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("\"posts\": [");

        for(int i=0; i<postings.size(); i++) {
            Posting posting = postings.get(i);
            if (i > 0) sb.append(",");
            sb.append(String.format(
                    "{\"id\": %s, \"title\": \"%s\",\"author\": \"%s\"}",
                    posting.getId(), posting.getTiltle(), posting.getAuthor()
            ));
        }

        sb.append("]");
        sb.append("}");
        return sb.toString();
    }
}
